<template>
  <el-dialog :title="title" :visible.sync="visible" class="dialog-md" append-to-body @close="visible = false">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="80px" v-loading="loading">
      <el-row>
        <el-col :span="form.id ? 24 : 12">
          <el-form-item label="用户名称" prop="user_name">
            <el-input v-model="form.user_name" placeholder="请输入用户名称" maxlength="30" :disabled="!!form.id"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item v-if="!form.id" label="用户密码" prop="password">
            <el-input v-model="form.password" placeholder="请输入用户密码" type="password" maxlength="20" show-password/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用户昵称" prop="nick_name">
            <el-input v-model="form.nick_name" placeholder="请输入用户昵称" maxlength="30" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="归属部门" prop="deptId">
            <TreeSelect v-model="form.deptId" :options="deptOptions" :normalizer="normalizer" show-count placeholder="请选择归属部门" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号码" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入手机号码" maxlength="11" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="用户性别">
            <el-select v-model="form.sex" placeholder="请选择性别">
              <el-option
                v-for="dict in dict.type.sys_user_sex"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态">
            <el-radio-group v-model="form.status">
              <el-radio
                v-for="dict in dict.type.sys_normal_disable"
                :key="dict.value"
                :label="dict.value"
              >{{dict.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="岗位" prop="postIds">
            <el-select v-model="form.postIds" multiple placeholder="请选择岗位">
              <el-option v-for="item in postOptions" :key="item.id" :label="item.name" :value="item.id" :disabled="item.status !== '1'"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="角色" prop="roleIds">
            <el-select v-model="form.roleIds" multiple placeholder="请选择角色">
              <el-option v-for="item in roleOptions" :key="item.id" :label="item.name" :value="item.id" :disabled="item.status !== '1'" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="头像" prop="avatar">
        <image-upload :default-list="defaultAvatar" v-model="form.avatar" :limit="1" over-hide-upload />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
      </el-form-item>
    </el-form>
    <div class="dialog-footer">
      <el-button type="primary" @click="handleSubmit" :loading="submitting" :disabled="loading">确 定</el-button>
      <el-button @click="visible = false">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { infoAdminApi, editAdminApi, addAdminApi } from '@/api/system/admin'
import { selectDeptApi } from '@/api/system/dept'
import { selectRoleApi } from '@/api/system/role'
import { selectPostApi } from '@/api/system/post'
import TreeSelect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

export default {
  name: 'UserForm',
  dicts: ['sys_normal_disable', 'sys_user_sex'],
  components: { TreeSelect },
  props: {
    value: Boolean, // 用来v-model显示隐藏
    row: Object, // 编辑时传入行数据
  },
  data() {
    return {
      title: '',
      loading: true, // 打开时数据加载中
      submitting: false, // 提交进行中
      deptOptions: [],
      roleOptions: [],
      postOptions: [],
      defaultAvatar: '', // 头像默认值
      form: {
        user_name: undefined,
        nick_name: undefined,
        deptId: undefined,
        roleIds: [],
        postIds: [],
        phone: undefined,
        email: undefined,
        sex: undefined,
        status: '1',
        remark: undefined
      }
    }
  },
  computed: {
    rules(){
      const common = {
        user_name: [
          { required: true, message: "用户名称不能为空", trigger: "blur" },
          { min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        nick_name: [{ required: true, message: "用户昵称不能为空", trigger: "blur" }],
        email: [{ type: "email", message: "请输入正确的邮箱地址", trigger: ["blur", "change"] }],
        roleIds: [ {required: true, message: "请选择角色", trigger: "blur" }],
        phone: [{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }]
      }
      const add = {
        password: [
          { required: true, message: "用户密码不能为空", trigger: "blur" },
          { min: 6, max: 20, message: '用户密码长度必须介于 6 和 20 之间', trigger: 'blur' },
          { pattern: /^[^<>"'|\\]+$/, message: "不能包含非法字符：< > \" ' \\\ |", trigger: "blur" }
        ],
      }
      this.$nextTick(() => this.$refs.formRef.clearValidate())
      if (!this.form.id) return { ...common,...add }
      return common
    },
    visible: {
      get() {
        return this.value
      },
      set(val) {
        this.$emit('input', val)
      }
    },
  },
  created() {
    this.init()
  },
  methods: {
    async init() {
      this.loading = true
      this.form.id = this.row?.id || undefined
      if (this.form.id) {
        this.title = '编辑用户'
        await this.getRowData()
      } else {
        this.form.deptId = this.row?.deptId || undefined
        this.title = '添加用户'
      }
      await this.getRoleOptions()
      await this.getPostOptions()
      await this.getDeptOptions()
      this.loading = false
    },
    async handleSubmit() {
      this.$refs.formRef.validate(async valid=>{
        if(!valid || this.submitting) return
        this.submitting = true
        try {
          if (this.form.id) {
            await editAdminApi(this.form)
          } else {
            await addAdminApi(this.form)
          }
          this.$emit('submit')
          this.$modal.msgSuccess('操作成功')
          this.visible = false
        } catch (e) {
          this.submitting = false
        }
      })
    },
    async getRowData() {
      try {
        const { info } = await infoAdminApi(this.form.id)
        this.form = this.dataToForm(this.form, info, true)
        this.defaultAvatar = info?.avatar || ''
      } catch (error) {
        this.visible = false
      }
    },
    async getDeptOptions() {
      try {
        const res = await selectDeptApi()
        this.deptOptions = this.listToTree(res?.list || [])
      } catch (e) {}
    },
    async getPostOptions() {
      try {
        const res = await selectPostApi()
        this.postOptions = res?.list || []
      } catch (e) {}
    },
    async getRoleOptions() {
      try {
        const res = await selectRoleApi()
        this.roleOptions = res?.list || []
      } catch (e) {}
    },
    normalizer(node) {
      if (node.children && !node.children.length) delete node.children
      return {
        id: node.id,
        label: node.name,
        children: node.children,
        isDisabled: node.status !== '1'
      }
    }
  }
}
</script>
